//
//  PicturesViewController.m
//  HuateVideo
//
//  Created by  on 12-5-30.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "PicturesViewController.h"
#import "PicShowViewController.h"
#import "CommonWebServices.h"
#import "DataList.h"
#import "Movie.h"
@interface PicturesViewController ()
- (void)loadData;

- (NSArray*)bundleArrayWithName:(NSString*)bundleName;
@end

@implementation PicturesViewController

-(void)viewWillDisappear:(BOOL)animated{
	[super viewWillDisappear:animated];
	if (downloaderArray.count) {
        [downloaderArray makeObjectsPerformSelector:@selector(cancelDownload)];
    }	
}

- (void)dealloc{
	[downloaderArray release];
	[typeArray release];
	[yearArray release];
	[parma release];
    [array release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        array=[[NSMutableArray alloc] init];
		parma=[[NSMutableDictionary alloc] init];
		typeArray=[[NSMutableArray alloc] init];
		yearArray=[[NSMutableArray alloc] init];
		[yearArray addObjectsFromArray:[self bundleArrayWithName:@"DateFilter"]];
		[typeArray addObjectsFromArray:[self bundleArrayWithName:@"PicType"]];

		[parma setValue:@"0" forKey:@"Num"];
		[parma setValue:@"20" forKey:@"PageSize"];
		[parma setValue:@"1" forKey:@"PageNow"];
        downloaderArray=[[NSMutableArray alloc] init];

		typeFilter=@"全部";
		yearFilter=@"全部";
        
        [parma setValue:@"全部" forKey:@"year"];
		[parma setValue:@"全部" forKey:@"type"];

    }
    return self;
}

- (NSArray*)bundleArrayWithName:(NSString*)bundleName{
	NSString* filePath=[[NSBundle mainBundle] pathForResource:bundleName ofType:@"plist"];
	NSArray* arrar=[NSArray arrayWithContentsOfFile:filePath];
	return arrar;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=TOOLBAR_TINTCOLOR;
	// Do any additional setup after loading the view.
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460-44-49)];
    table.dataSource = self;
    table.delegate = self;
    table.allowsSelection=NO;
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    table.backgroundColor = [UIColor clearColor];
    [self.view addSubview:table];
    [table release];
	
	UIBarButtonItem*cate=[[UIBarButtonItem alloc] initWithTitle:LS(@"筛选") style:UIBarButtonItemStylePlain target:self action:@selector(toShuaixian)];
	self.navigationItem.rightBarButtonItem=cate;
	[cate release];
	
    [self loadData];
}

- (void)loadData{
	[self.view showProgressText:YES];
	CommonWebServices *webServ = [[CommonWebServices alloc] init];
    webServ.delegate = self;
    [webServ startRequestWithMode:@"Default" Action:@"GetPictureByScreenType" Parma:parma Class:@"DataList" RootXML:@"GetPictureByScreenTypeResult" resultIsArray:YES];
    [webServ release];
}

- (void)onCommonWebServicesWithCustomClass:(id)object {
    NSArray *movieList = ((DataList *)object).List;
    
    if ([movieList count]>0) {
        [array addObjectsFromArray:movieList];
        [table reloadData];
    }
    
    [self.view showProgressText:NO];
}


- (void)onCommonWebServicesFaild
{
    NSLog(@">>>>>>>>:加载失败");
    [self.view showProgressText:NO];
}
#pragma mark --
- (void)toShuaixian
{
    if (_actionSheet==nil) {
        _actionSheet = [[UIActionSheet alloc]initWithTitle:nil 
                                                  delegate:nil
                                         cancelButtonTitle:nil
                                    destructiveButtonTitle:nil
                                         otherButtonTitles:nil];
        _actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
        UISegmentedControl *closeButton = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObject:@"取消"]];
        closeButton.momentary = YES;
        closeButton.tag=1;
        closeButton.frame = CGRectMake(10, 7, 50, 30);
        closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
        closeButton.tintColor = [UIColor blackColor];
        [closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
        [_actionSheet addSubview:closeButton];
        [closeButton release];
        
        UILabel*year=[[UILabel alloc] initWithFrame:CGRectMake(10, 40, 100, 30)];
        year.text=LS(@"时间");
        year.textAlignment=UITextAlignmentCenter;
        year.textColor=[UIColor whiteColor];
        year.backgroundColor=[UIColor clearColor];
        [_actionSheet addSubview:year];
        [year release];
        
        UILabel*type=[[UILabel alloc] initWithFrame:CGRectMake(110, 40, 100, 30)];
        type.text=LS(@"类型");
        type.textAlignment=UITextAlignmentCenter;
        type.textColor=[UIColor whiteColor];
        type.backgroundColor=[UIColor clearColor];
        [_actionSheet addSubview:type];
        [type release];
	
		year.frame=CGRectMake(10, 40, 150, 30);
		type.frame=CGRectMake(150, 40, 150, 30);
    
		UISegmentedControl *doneButton = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObject:@"确定"]];
        doneButton.momentary = YES;
        doneButton.tag=1;
        doneButton.frame = CGRectMake(260, 7, 50, 30);
        doneButton.segmentedControlStyle = UISegmentedControlStyleBar;
        doneButton.tintColor = [UIColor blackColor];
        [doneButton addTarget:self action:@selector(doActionSheet:) forControlEvents:UIControlEventValueChanged];
        [_actionSheet addSubview:doneButton];
        [doneButton release];
        
    }
    if (_pickerView==nil) {
        _pickerView = [[UIPickerView alloc]initWithFrame:CGRectZero];
        _pickerView.frame = CGRectMake(0, 70, 320, 216);
        _pickerView.showsSelectionIndicator = YES;
        _pickerView.delegate = self;
        _pickerView.dataSource=self;
        [_actionSheet addSubview:_pickerView];
    }
    [_actionSheet showFromRect:CGRectMake(0, 0, 320, 260) inView:self.view animated:YES];
    [_actionSheet setBounds:CGRectMake(0, 0, 320, 585)];
}


-(void)dismissActionSheet:(id)sender{
	if (![yearFilter isEqualToString:[parma valueForKey:@"year"]]) {
		yearFilter=[parma valueForKey:@"year"];
		NSInteger index0=[yearArray indexOfObject:yearFilter];
		[_pickerView selectRow:index0 inComponent:0 animated:NO];
	}
	if (![typeFilter isEqualToString:[parma valueForKey:@"type"]]) {
		typeFilter=[parma valueForKey:@"type"];
		NSInteger index1=[typeArray indexOfObject:typeFilter];
		[_pickerView selectRow:index1 inComponent:1 animated:NO];
	}
    [_actionSheet dismissWithClickedButtonIndex:0 animated:YES];
    
}


-(void)doActionSheet:(id)sender{
    [_actionSheet dismissWithClickedButtonIndex:0 animated:YES];
	[self loadData];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
        return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
        if (component==0) {
            return yearArray.count;
        }else {
            return typeArray.count;
        }
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component==0) {
        return LS([yearArray objectAtIndex:row]);
    }
    else  {
        return LS([typeArray objectAtIndex:row]);    
	}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
		switch (component) {
			case 0:
				yearFilter=[yearArray objectAtIndex:row];

				break;
			case 1:
				typeFilter=[typeArray objectAtIndex:row];
				
				break;
			default:
				break;
		}

}


#pragma mark --


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    int m=array.count%3;
    int n=array.count/3;
    if (m) {
        return n+1;
    }else {
        return n;
    }
}
- (void)downImg:(NSDictionary*)dic {
	id movie=[dic valueForKey:@"item"];
	int tag=[[dic valueForKey:@"rowNum"] intValue];
	ImageDownloader* downloader=[[ImageDownloader alloc] init];
	downloader.imageURL=[movie News_pic];
	downloader.delegate=self;
	downloader.tag=tag;
	[downloader startDownload:YES];
	[downloaderArray addObject:downloader];
	[downloader release];
	
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	static NSString* ListIdentifier = @"ListIdentifier";
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:ListIdentifier];
	
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ListIdentifier] autorelease];
		//cell.selectionStyle = UITableViewCellSelectionStyleNone;  //去掉选中时的颜色
	}
    for (UIView* subView in [cell.contentView subviews])
	{
		[subView removeFromSuperview];
	}
    for (int i=0; i<3; i++) {
        if (3*indexPath.row + i < array.count) {
            id picItem=[array objectAtIndex:indexPath.row*3+i];
            UIButton* im = [UIButton buttonWithType:UIButtonTypeCustom];
			im.tag=3*indexPath.row + i+1000;
			if (![picItem iconImg]) {
				[im setBackgroundImage:[UIImage imageNamed:@"dengdai.png"] forState:UIControlStateNormal];
				NSDictionary* dic=[NSDictionary dictionaryWithObjectsAndKeys:picItem,@"item",[NSNumber numberWithInt:indexPath.row*3+1000+i],@"rowNum",nil];
				[self performSelector:@selector(downImg:) withObject:dic afterDelay:0.3];

			}else {
				[im setBackgroundImage:[picItem iconImg] forState:UIControlStateNormal];
			}

            [im addTarget:self action:@selector(seePic:) forControlEvents:UIControlEventTouchUpInside];
            im.frame=CGRectMake(16+107*(i%3), 10+95*(i/3), 75, 95);
            [cell.contentView addSubview:im];
            
//            UILabel* la=[[UILabel alloc] initWithFrame:CGRectMake(10+110*(i%3), 108+100*(i/3), 80, 20)];
//            la.backgroundColor=[UIColor clearColor];
//            la.textAlignment=UITextAlignmentCenter;
//            la.textColor=[UIColor whiteColor];
//            la.text=[picItem News_title];
//            [cell.contentView addSubview:la];
//            [la release];
        }
    }
    UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 113, 320, 2)];
    line.image = [UIImage imageNamed:@"fengexian.png"];
    [cell.contentView addSubview:line];
    [line release];
    return cell;
}
#pragma mark imagedownloaderDelegate
- (void)appImageDidLoad:(UIImage *)image withTag:(int)tag{
    NSLog(@"load >>>>>>>>>>>%d",tag);
	id t_movie=[array objectAtIndex:tag-1000];
    UITableViewCell* cell=[table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:((tag-1000)/3) inSection:0]];
    UIButton* img=(UIButton*)[cell.contentView viewWithTag:tag];
    if (image) {
		[t_movie setIconImg:image];
		[img setBackgroundImage:image forState:UIControlStateNormal];
    }
}

-(void)seePic:(UIButton*)btn{
	id item=[array objectAtIndex: btn.tag-1000];
    PicShowViewController*picshow=[[PicShowViewController alloc] init];
    picshow.imgCount=btn.tag-1000;
	picshow.picListArray=[NSArray arrayWithArray:array];
    [self.navigationController pushViewController:picshow animated:YES];
    [picshow release];
    
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
